/**
 * Created by Zhao Bo En on 2017/12/05 0024.
 */
//日期转换
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var WfMetSk = null;//风电场风速风向实况表
var WfNwpSk = null;//风电场风速风向预报表
var WfMet0to3 = null;  //实况speed为0-3
var WfMet3to6 = null;  //实况speed为3-6
var WfMet6to9 = null;  //实况speed为6-9
var WfMet9to12 = null;  //实况speed为9-12
var WfMet12 = null;  //实况speed>=12
var WfNwp0to3 = null //预报speed为0-3;
var WfNwp3to6 = null;
var WfNwp6to9 = null;
var WfNwp9to12 = null;
var WfNwp12 = null;
var WfNwpForTime = new Array();//实况数据
var startTime = null;       //开始时间，表格导出数据使用
var endTime = null;         //结束时间，表格导出数据使用
var farmName = null;       //电场名称，表格导出数据使用
var fileName = null;
$(function () {
    //$.ajaxSettings.async = false;
    loadTower();//加载测风塔
    dateTiemSelect();
    $("#query").click(function () {
        // alert("111");
        if($("#startTime").val()===""){
            layer.msg("输入开始时间！", {icon: 2});
            $("#endTime").val("");
        }
        var startTime = new Date($("#startTime").val().replace(/\-/g, "\/"));
        var endTime = new Date($("#endTime").val().replace(/\-/g, "\/"));
        if(startTime >=endTime){
            layer.msg("开始时间不能大于结束时间！", {icon: 2});
            $("#startTime").val("");
            $("#endTime").val("");
            return false;
        }else {
            load();
        }
    })


    var aa = $('#selectFarm', window.parent.document).find("option:selected").text();
    console.log(aa);
    //  fileName = aa.substring(31,aa.length);
    // console.log(fileName);
    startTime = $("#startTime").val();
    endTime = $("#endTime").val();

    var table = new tableFactory(startTime,endTime,aa);


})
//点击时间查询
function dateTiemSelect(){
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render({
            elem: '#startTime', //新增的日期
            type: 'date',//日期类型date表示年月日
            /*  trigger: 'click',//如果绑定的元素非输入框，则默认事件为：click*/
            theme: '#2a2a48',//自定义主题
            min: '2014-1-1',//限制最小日期
            max: '2028-12-31'//限制最大日期
        });
        laydate.render({
            elem: '#endTime', //新增的日期
            type: 'date',
            theme: '#2a2a48',//自定义主题
            max: '2028-12-31',//限制最大日期
            ready: function(date){
                //console.log(date); //得到初始的日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            },
            /*change: function(value, date, endDate){ //日期时间被切换后的回调
                console.log(value); //得到日期生成的值，如：2017-08-18
                console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            }*/
            done: function(value, date, endDate){//选中之后的对调函数
                //得到日期生成的值，如：2017-08-18
                // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                //console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            }
        });
    });
}

function loadTower(){
    $("#tower").empty();//赋值之前，先清空
    var me = this;
    var index = layer.load(1);
    var farmid = $('#selectFarm', window.parent.document).val();
    var news = $("#tower");//获取测风塔对象
    var data = {"farmid":farmid};
    $.ajax({
        url : "../windCurvesManage/getTower",
        type : "get",
        async:false,
        contentType : "application/json",
        dataType : "json",
        data :data /*JSON.stringify(data)*/,//转换成字符串。后台使用了RequestBody注解
        success : function(data) {
            if(data.listTowerno.length>0){
                for(var i = 0;i<data.listTowerno.length;i++){
                    if(data.listTowerno[i] == data.thisTowerno){
                        news.append('<option value="'+data.listTowerno[i]+'" selected = "selected">'+data.listTowermodel[i]+'</option>');
                    }else {
                        news.append('<option value="'+data.listTowerno[i]+'">'+data.listTowermodel[i]+'</option>');
                    }
                }

            }else {
                news.append('<option value="'+404404404+'">'+'无'+'</option>');
            }


            $("#tower").selectpicker('refresh');
            load();
            layer.close(index);
        }
    });
    $("#tower").selectpicker();
}

//初始化加载玫瑰图数据跟表格数据
function load(){
    var index = layer.load(1);
    //实况
    var live0to3 = new Array();
    var live3to6 = new Array();
    var live6to9 = new Array();
    var live9to12 = new Array();
    var live12 = new Array();
    //预报
    var forecast0to3 = new Array();
    var forecast3to6 = new Array();
    var forecast6to9 = new Array();
    var forecast9to12 = new Array();
    var forecast12 = new Array();
    var farmid = $('#selectFarm', window.parent.document).val();//获取父页面的元素
    var tower = $("#tower option:checked").val();
    var p = {
        "startTime":$("#startTime").val(),
        "endTime":$("#endTime").val(),
        "farmid":farmid,
        "towerid":tower,
    };

    //取所有数据
    $.ajax({
        url : "../roseManage/selectMetAndNwp",
        type : "get",
        contentType : "application/json",
        dataType : "json",
        data : p,
        success : function(data) {
            /*getWfNwpSk(p);
            getWfMetForTimeData(p);
            //实况数据
            getWfMet0to3(p);
            getWfMet3to6(p);
            getWfMet6to9(p);
            getWfMet9to12(p);
            getWfMet12(p);
            //预报数据
            getWfNwp0to3(p);
            getWfNwp3to6(p);
            getWfNwp6to9(p);
            getWfNwp9to12(p);
            getWfNwp12(p);*/
            WfNwpForTime = new Array;
            if(data.wfNwpSk.length>0){
                $.each(data.wfNwpSk, function (index, item) {
                    var time1 = new Date(parseInt(item.foretime)).Format("yyyy-MM-dd hh:mm");
                    if(item.winddirection!=null && item.windspeed!=null){
                        var s = {Winddirection:item.winddirection.toFixed(1),Windspeed:item.windspeed.toFixed(2),Foretime:time1};
                        WfNwpForTime.push(s)
                    }
                });
            }

            WfMetSk = data.wfMetSk;

            if(data.wfMetSk.length>0){
                WfMet0to3 = data.live0to3;
                WfMet3to6 = data.live3to6;
                WfMet6to9 = data.live6to9;
                WfMet9to12 = data.live9to12;
                WfMet12 = data.live12;
                for(var i = 0;i<WfMet0to3.length;i++){
                    live0to3.push(WfMet0to3[i].toFixed(2));
                    live3to6.push(WfMet3to6[i].toFixed(2));
                    live6to9.push(WfMet6to9[i].toFixed(2));
                    live9to12.push(WfMet9to12[i].toFixed(2));
                    live12.push(WfMet12[i].toFixed(2));
                }
            }
            if(data.wfNwpSk.length>0){
                WfNwp0to3 = data.forecast0to3;
                WfNwp3to6 = data.forecast3to6;
                WfNwp6to9 = data.forecast6to9;
                WfNwp9to12 = data.forecast9to12;
                WfNwp12 = data.forecast12;
                for(var i = 0;i<WfNwp0to3.length;i++){
                    forecast0to3.push(WfNwp0to3[i].toFixed(2));
                    forecast3to6.push(WfNwp3to6[i].toFixed(2));
                    forecast6to9.push(WfNwp6to9[i].toFixed(2));
                    forecast9to12.push(WfNwp9to12[i].toFixed(2));
                    forecast12.push(WfNwp12[i].toFixed(2));
                }
            }

            $("#rose").bootstrapTable("load", WfNwpForTime);
            lodaTu(live0to3,live3to6,live6to9,live9to12,live12,forecast0to3,forecast3to6,forecast6to9,forecast9to12,forecast12);
            layer.close(index);

        },
    });

}
/*//speed 0-3
function getWfMet0to3(p){
    $.getJSON('/roseManage/select0to3',p, function (_data) {
        WfMet0to3= _data;
    })
}
//speed 3-6
function getWfMet3to6(p){
    $.getJSON('/roseManage/select3to6',p, function (_data) {
        WfMet3to6= _data;
    })
}
//speed 6-9
function getWfMet6to9(p){
    $.getJSON('/roseManage/select6to9',p, function (_data) {
        WfMet6to9= _data;
    })
}
//speed 9-12
function getWfMet9to12(p){
    $.getJSON('/roseManage/select9to12',p, function (_data) {
        WfMet9to12= _data;
    })
}
//speed >=12
function getWfMet12(p){
    $.getJSON('/roseManage/selectGreater12',p, function (_data) {
        WfMet12= _data;
    })
}

//预报

//speed 0-3
function getWfNwp0to3(p){
    $.getJSON('/roseManage/select0to3Forecast',p, function (_data) {
        WfNwp0to3= _data;
    })
}
//speed 3-6
function getWfNwp3to6(p){
    $.getJSON('/roseManage/select3to6Forecast',p, function (_data) {
        WfNwp3to6= _data;
    })
}
//speed 6-9
function getWfNwp6to9(p){
    $.getJSON('/roseManage/select6to9Forecast',p, function (_data) {
        WfNwp6to9= _data;
    })
}
//speed 9-12
function getWfNwp9to12(p){
    $.getJSON('/roseManage/select9to12Forecast',p, function (_data) {
        WfNwp9to12= _data;
    })
}
//speed >=12
function getWfNwp12(p){
    $.getJSON('/roseManage/selectGreater12Forecast',p, function (_data) {
        WfNwp12= _data;
    })
}
//获取预报数据
function getWfNwpSk(p) {
    $.getJSON('/roseManage/selectForecast',p, function (_data) {
        WfNwpSk= _data;
    })
}

// 按时间顺序获取风场实况数据
function getWfMetForTimeData(p) {

    $.ajax({    //按时间顺序获取实况数据
        url : "/roseManage/selectAllForTime",
        type : "get",
        contentType : "application/json",
        dataType : "json",
        data : p,
        success : function(data) {
            $.each(data, function (index, item) {
                var time1 = new Date(parseInt(item.observetime)).Format("yyyy-MM-dd hh:mm");
                var s = {Winddirection:item.winddirection.toFixed(1),Windspeed:item.windspeed.toFixed(2),Observetime:time1,Farmid:item.farmid};
                WfMetForTime.push(s)
            });

        },
        error :function(){
            alert("加载失败");
        }
    })
}*/

//表格样式
function tableFactory(startTime,endTime,fileNames) {
    var me = this;
    me.data = null;//有功功率
    me.windData = null;//电站信息
    var init = function () {
        $.when(me.getWindData()).then(function () {
            $("#rose").bootstrapTable({
                method: 'get',				  //请求方式（*）
                striped: true,					  //是否显示行间隔色
                cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,				   //是否显示分页（*）
                sortable: true,					 //是否启用排序
                sortOrder: "desc",				   //排序方式
                sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,					   //初始化加载第一页，默认第一页
                search: true,					   //是否显示表格搜索，只能进行客户端搜索
                strictSearch: false,                //true为全匹配，false为模糊查询
                showColumns: true,				  //是否显示筛选列按钮
                showRefresh: true,			  //是否显示刷新按钮
                clickToSelect:true,				//是否启用点击选中行
                showToggle: false,					//是否显示详细视图和列表视图的切换按钮
                cardView: false,					//是否显示详细视图
                detailView: false,				   //是否显示父子表
                singleSelect: true,                //是否支持多选,false表示支持多选，true表示不支持
                //undefinedText: '_',              //当数据为undefined时显示的字符
                height: 'auto',
                pageSize: 5,
                pageList: [5,20,30],
                editable:true,//是否可以行内编辑
                showExport: true,//是否显示导出按钮
                exportDataType:'all',//导出全部
                exportTypes:[  'csv'], //导出文件类型
                export: 'glyphicon-export icon-share',
                exportOptions:{
                    // ignoreColumn: [0,1],  //忽略某一列的索引
                    fileName:startTime+"_"+endTime+"_"+fileNames,  //文件名称设置
                    // worksheetName: 'sheet1',  //表格工作区名称
                    // tableName: '总台帐报表',
                    //  excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],
                    // onMsoNumberFormat: DoOnMsoNumberFormat
                },
                columns: [
                    {
                        title: '观测时间',
                        field: 'Foretime',
                        sortable: true,//排序
                        align: 'center',
                        valign: 'middle',
                    },{
                    title: '实际风向(°)',
                    field: '',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        return me.getWfMetSkDirection(row.Foretime);
                    }
                },{
                    title: '预报风向(°)',
                    field: 'Winddirection',
                    align: 'center',
                    valign: 'middle',

                },

                    {
                    title: '实际风速(m/s)',
                    field: '',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        return me.getWfMetSkSpeed(row.Foretime);
                    }
                },{
                        title: '预报风速(m/s)',
                        field: 'Windspeed',
                        align: 'center',
                        valign: 'middle',

                    },
                    ],
                onEditableSave: function (field, row, oldValue, $el) {//编辑之后的事件
                    var p ={
                        id:row.fid,
                        power:row.power
                    }
                    $.ajax({
                        type: "post",
                        url: "../roseManage/edit",
                        data:row,//后台使用了实体类，前台就不能用Json.stringify
                        dataType: 'JSON',
                        success: function (data, status) {
                            /*if (status == "success") {
                                alert('提交数据成功');
                            }*/
                        },
                        error: function () {
                            alert('编辑失败');
                        },
                        complete: function () {

                        }

                    });
                }
            });
            //me.loadData();
            load();
        });
    }
    init();
}

tableFactory.prototype = {

    //加载电站信息
    getWindData:function () {
        var me = this;
        $.getJSON('../windManage/selectAll', '', function (_data) {
            me.WindData = _data;
        })
    },
    getWindById: function (farmid) {
        var farmName = '';
        var me = this;
        $.each(me.WindData, function (index, item) {
            if (item.farmid === farmid) {
                farmName = item.farmname;
                return false;
            }
        });
        return farmName;
    },

    //获取实际风速
    getWfMetSkSpeed:function (Foretime) {
        var speed="";
        if(WfMetSk.length>0){
            $.each(WfMetSk, function (index, item) {
                var WfMetSkTime = new Date(parseInt(item.observetime)).Format("yyyy-MM-dd hh:mm")
                if(WfMetSkTime==Foretime) {
                    if(item.windspeed!=null){
                        speed = item.windspeed.toFixed(2);
                    }else {
                        speed = "-";
                    }

                    return false;
                }
            });
            return speed;
        }
    },

    //获取预报风向
    getWfMetSkDirection:function (Foretime) {
        var direction="";
        if(WfMetSk.length>0){
            $.each(WfMetSk, function (index, item) {
                var WfMetSkTime = new Date(parseInt(item.observetime)).Format("yyyy-MM-dd hh:mm")
                if(WfMetSkTime==Foretime) {
                    if(item.winddirection!=null){
                        direction = item.winddirection.toFixed(1);
                    }else {
                        direction = "-";
                    }

                    return false;
                }
            });
            return direction;
        }
    },

}
//玫瑰图
function lodaTu(live0to3,live3to6,live6to9,live9to12,live12,forecast0to3,forecast3to6,forecast6to9,forecast9to12,forecast12) {
    //实况玫瑰图
    var myChart = echarts.init(document.getElementById("main"));
    option = {
        title:{
            text:'实况',
            subtext:'新能源',
            left:'center',
            textStyle: {
                color: '#fff'
            }
        },
        center:['50%','55%'],//图的位置
        angleAxis: {

            type: 'category',
            data: ['0°', '22.5°', '45°', '67.5°', '90°', '112.5°', '135°','157.5°','180°','202.5°','225°','247.5°','270°','292.5°','315°','337.5°'],
            axisLabel:{
                show:true,
                textStyle:{
                    fontSize:15,
                    color:'white'
                }
            },
            z: 0,
            boundaryGap: false,
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#fff',
                    type: 'solid'
                }
            },
            axisLine: {
                show: false
            }
        },
        radiusAxis: {
            show:true,
            axisLabel:{
                show:true,
                textStyle:{
                    fontSize:10,
                    color:'#fff'
                }
            }
        },
        polar: {
            center:['50%','55%'],//图的位置
        },
        series: [{
            type: 'bar',
            //data: [1.81, 0.62, 0.82, 0.59,0.62, 1.22, 1.61, 2.04,  2.66 ,2.96 ,2.53 ,1.97 ,1.64 ,1.32 ,1.58 ,1.51],
            data:live0to3,
            coordinateSystem: 'polar',
            name: '0m/s-3m/s(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'rgb(124, 181, 236)'
                }
            }
        }, {
            type: 'bar',
            //data: [1.78, 1.09, 0.82, 1.22,2.20, 2.01, 3.06, 3.42,  4.74 ,4.14 ,4.01 ,2.66 ,1.71 ,2.40 ,4.28 , 5.00],
            data:live3to6,
            coordinateSystem: 'polar',
            name: '3m/s-6m/s(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'#e0290b'
                }
            }
        }, {
            type: 'bar',
            //data: [0.16, 0.00, 0.07, 0.07,0.49, 1.55, 2.37, 1.97,  0.43 ,0.26 ,1.22 ,1.97 ,0.92 ,0.99 ,1.28 ,1.32],
            data:live6to9,
            coordinateSystem: 'polar',
            name: '6m/s-9m/s(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'#008B8B'
                }
            }
        }, {
            type: 'bar',
            //data: [0.00, 0.00, 0.00, 0.00,0.00, 0.30, 2.14, 0.86,  0.00 ,0.00 ,0.49 ,0.79 ,1.45 ,1.61 ,0.76 ,0.13],
            data:live9to12,
            coordinateSystem: 'polar',
            name: '9m/s-12m/s(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'rgb(247, 163, 92)'
                }
            }
        }, {
            type: 'bar',
            //data: [0.00, 0.00, 0.00, 0.00,0.00, 0.13, 1.74, 0.53,  0.00 ,0.00 ,0.13 ,0.30 ,0.26 ,0.33 ,0.66 ,0.23],
            data:live12,
            coordinateSystem: 'polar',
            name: '12m/s以上(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'rgb(128, 133, 233)'
                }
            }
        }
        ],
        legend: [

            {
                show: true,
                top:'top',
                left:'left',
                data: ['0m/s-3m/s(%)', '3m/s-6m/s(%)', '6m/s-9m/s(%)','9m/s-12m/s(%)','12m/s以上(%)'],
                orient:'vertical',
                textStyle: {
                    color: '#fff',
                    fontSize: 10
                }
            }
        ],
        tooltip: {
            trigger: 'axis',

        },
    };
    myChart.setOption(option);

    //预报玫瑰图 -------------------------------------------------------------------------------------------
    //预报玫瑰图 -------------------------------------------------------------------------------------------
    //预报玫瑰图 -------------------------------------------------------------------------------------------

    var myChart = echarts.init(document.getElementById("main2"));
    option2 = {
        title:{
            text:'预报',
            subtext:'新能源',
            left:'center',
            textStyle: {
                color: '#fff'
            }
        },
        center:['50%','55%'],//图的位置
        angleAxis: {

            type: 'category',
            data: ['0°', '22.5°', '45°', '67.5°', '90°', '112.5°', '135°','157.5°','180°','202.5°','225°','247.5°','270°','292.5°','315°','337.5°'],
            axisLabel:{
                show:true,
                textStyle:{
                    fontSize:15,
                    color:'white'
                }
            },
            z: 0,
            boundaryGap: false,
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#fff',
                    type: 'solid'
                }
            },
            axisLine: {
                show: false
            }
        },
        radiusAxis: {
            show:true,
            axisLabel:{
                show:true,
                textStyle:{
                    fontSize:10,
                    color:'#fff'
                }
            }
        },
        polar: {
            center:['50%','55%'],//图的位置
        },
        series: [{
            type: 'bar',
            //data: [1.81, 0.62, 0.82, 0.59,0.62, 1.22, 1.61, 2.04,  2.66 ,2.96 ,2.53 ,1.97 ,1.64 ,1.32 ,1.58 ,1.51],
            data:forecast0to3,
            coordinateSystem: 'polar',
            name: '0m/s-3m/s(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'rgb(124, 181, 236)'
                }
            }
        }, {
            type: 'bar',
            //data: [1.78, 1.09, 0.82, 1.22,2.20, 2.01, 3.06, 3.42,  4.74 ,4.14 ,4.01 ,2.66 ,1.71 ,2.40 ,4.28 , 5.00],
            data:forecast3to6,
            coordinateSystem: 'polar',
            name: '3m/s-6m/s(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'#e0290b'
                }
            }
        }, {
            type: 'bar',
            //data: [0.16, 0.00, 0.07, 0.07,0.49, 1.55, 2.37, 1.97,  0.43 ,0.26 ,1.22 ,1.97 ,0.92 ,0.99 ,1.28 ,1.32],
            data:forecast6to9,
            coordinateSystem: 'polar',
            name: '6m/s-9m/s(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'#008B8B'
                }
            }
        }, {
            type: 'bar',
            //data: [0.00, 0.00, 0.00, 0.00,0.00, 0.30, 2.14, 0.86,  0.00 ,0.00 ,0.49 ,0.79 ,1.45 ,1.61 ,0.76 ,0.13],
            data:forecast9to12,
            coordinateSystem: 'polar',
            name: '9m/s-12m/s(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'rgb(247, 163, 92)'
                }
            }
        }, {
            type: 'bar',
            //data: [0.00, 0.00, 0.00, 0.00,0.00, 0.13, 1.74, 0.53,  0.00 ,0.00 ,0.13 ,0.30 ,0.26 ,0.33 ,0.66 ,0.23],
            data:forecast12,
            coordinateSystem: 'polar',
            name: '12m/s以上(%)',
            stack: 'a',
            itemStyle:{
                normal:{
                    color:'rgb(128, 133, 233)'
                }
            }
        }
        ],
        /*legend: [

            {
                show: true,
                top:'top',
                left:'left',
                data: ['0m/s-3m/s(%)', '3m/s-6m/s(%)', '6m/s-9m/s(%)','9m/s-12m/s(%)','12m/s以上(%)'],
                orient:'vertical',
                textStyle: {
                    color: '#fff',
                    fontSize: 10
                }
            }
        ],*/
        tooltip: {
            trigger: 'axis',

        },
    };
    myChart.setOption(option2);
}
